<template>
  <lb-layout
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item prop="sysDeptList">
        <cascader-select
          v-model="queryParams.sysDeptList"
          :values="queryParams.sysDeptList"
          varient="energy"
          node-key="id"
          size="small"
          placeholder="请选择用能单位"
        ></cascader-select>
      </el-form-item>
      <el-form-item prop="targetType">
        <el-select
          v-model="queryParams.targetType"
          placeholder="请选择指标类型"
        >
          <el-option
            v-for="dict in dict.type.target_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="energyType">
        <el-select
          v-model="queryParams.energyType"
          placeholder="请选择能耗种类"
        >
          <el-option
            v-for="dict in dict.type.energy_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="rationCriterionVersion">
        <el-select
          v-model="queryParams.rationCriterionVersion"
          placeholder="请选择额度标准版本号"
        >
          <el-option
            v-for="dict in versionOption"
            :key="dict"
            :label="dict"
            :value="dict"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="allocationYear">
        <el-date-picker
          v-model="queryParams.allocationYear"
          type="year"
          value-format="yyyy"
          placeholder="请选择额度分配年份"
          :clearable="false"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
        <el-button
          v-hasPermi="['energy:allocation:quotaAllocation']"
          type="primary"
          plain
          size="small"
          @click="distribution"
          >额度批量分配</el-button
        >
        <el-button
          v-hasPermi="['energy:assess:import']"
          type="primary"
          plain
          size="small"
          @click="exportsShow = true"
          >导入实际能耗</el-button
        >
        <el-button
          v-hasPermi="['energy:allocation:export']"
          type="primary"
          plain
          size="small"
          @click="handleExport"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="totalList"
      :header-cell-style="tableHeaderCellStyle"
      :header-cell-class-name="headerRowStyle"
      border
      height="640"
    >
      <el-table-column
        prop="sysDeptName"
        label="用能单位"
        width="150"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="allocationYear"
        label="能耗分配年度"
        width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column label="年度计划预算（kwh/m2）" align="center">
        <template slot="header">
          <div class="flex">
            <div>年度计划预算（kwh/m2）</div>

            <el-popover
              placement="top-start"
              title="年度计划预算（kwh/m2）"
              trigger="hover"
            >
              <p style="width: 300px">
                算法模型使用①参考额度（引导值、基准值、约束值）、参考实际能耗，均默认使用“预分配年份N”的隔上一年（N-2）对应额度值、实际能耗值。②额度调幅采用本页面手工选择“额度标准版本号”对应调幅。
              </p>
              <i slot="reference" class="el-icon-info"></i>
            </el-popover>
          </div>
        </template>
        <el-table-column prop="assessGuideVal" label="引导值A0" align="center">
        </el-table-column>
        <el-table-column prop="assessBaseVal" label="基准值B0" align="center">
        </el-table-column>
        <el-table-column
          prop="assessConstraintVal"
          label="约束值C0"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column>
        <template slot="header">
          <div class="flex">
            <div>调整能耗额度（kwh/m2）</div>

            <el-popover
              placement="top-start"
              title="额度特殊调整规则"
              trigger="hover"
            >
              <p>①连续两年在约束值以上用能单位，三额度值均下调1%</p>
              <p>②连续两年在引导值以下用能单位，三额度值均上调1%</p>
              <p>③其它情况，额度按正常规则分配，不做调整。</p>
              <i slot="reference" class="el-icon-info"></i>
            </el-popover>
          </div>
        </template>
        <el-table-column prop="adjustGuideVal" label="引导值A1" align="center">
        </el-table-column>
        <el-table-column prop="adjustBaseVal" label="基准值B1" align="center">
        </el-table-column>
        <el-table-column
          prop="adjustConstraintVal"
          label="约束值C1"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" align="center" prop="caozuo" width="150">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.editEnable"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['energy:allocation:edit']"
              >修正</el-button
            >
            <el-button
              size="small"
              type="text"
              icon="el-icon-view"
              @click="detail(scope.row.id)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="实际分配能耗额度（kwh/m2）" align="center">
        <el-table-column
          prop="allocationGuideVal"
          label="引导值A2(A0+A1)"
          align="center"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="allocationBaseVal"
          label="基准值B2(B0+B1)"
          align="center"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="allocationConstraintVal"
          label="约束值C2(C0+C1)"
          align="center"
          width="160"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column
        prop="content"
        label="反馈信息"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page-sizes="[20, 40, 60, 80]"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 手工调整额度对话框 -->
    <el-dialog
      title="手工调整额度"
      :visible.sync="show"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="model" :rules="rules" label-width="100px">
        <el-form-item label="引导值" prop="adjustGuideVal">
          <el-input-number v-model="model.adjustGuideVal" />
        </el-form-item>
        <el-form-item label="基准值" prop="adjustBaseVal">
          <el-input-number v-model="model.adjustBaseVal" />
        </el-form-item>
        <el-form-item label="约束值" prop="adjustConstraintVal">
          <el-input-number v-model="model.adjustConstraintVal" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="close('form')">取 消</el-button>
      </div>
    </el-dialog>
    <exports
      :visible.sync="exportsShow"
      @close="hanleClose"
      @input="setImportDataId"
    ></exports>
    <detail :id="id" :visible.sync="detailShow" @close="close"></detail>
  </lb-layout>
</template>

  <script>
import {
  list,
  checkCommitEnable,
  quotaAllocation,
  quotaAllocationOpinion,
  adjustVal,
  totalEnergy,
} from "@/api/quota/allocation";
import { rationVersionList } from "@/api/quota/energy";
import auth from "@/plugins/auth";
import detail from "@/views/work/quota/allocation/components/detail.vue";
import CascaderSelect from "@/components/Select/CascaderSelect";
import { exportExecl } from "@/utils/export-execl";
import exports from "@/views/work/quota/energy/components/exports.vue";
import { mul, formatDate } from "@/utils/index";
export default {
  name: "allDistribution",
  filters: {
    dictFee(val) {
      const text = val ? mul(val, 100) + "%" : "";
      return text;
    },
    formatTime(val) {
      const text = val ? formatDate(val) : "";
      return text;
    },
  },
  dicts: ["energy_type", "target_type"],
  components: { CascaderSelect, detail, exports },
  data() {
    return {
      //   isNhgl: false, //能耗管理部门
      //   isYnbm: false, //用能人员
      id: "",
      detailShow: false,
      show: false,
      exportsShow: false,
      versionOption: [],
      // 遮罩层
      loading: true,
      // 表格树数据
      list: [],
      totalList: [],
      // 弹出层标题
      title: "",
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 24,
        sysDeptList: [],
        energyType: "",
        targetType: "",
        rationCriterionVersion: "",
        allocationYear: "",
      },
      model: {
        adjustGuideVal: 0,
        adjustBaseVal: 0,
        adjustConstraintVal: 0,
      },
      form: {
        content: "",
      },
      rules: {
        adjustBaseVal: [
          {
            required: true,
            message: "请输入基准值",
            trigger: ["change", "blur"],
          },
        ],
        adjustGuideVal: [
          {
            required: true,
            message: "请输入引导值",
            trigger: ["change", "blur"],
          },
        ],
        adjustConstraintVal: [
          {
            required: true,
            message: "请输入约束值",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  created() {
    // this.queryParams.allocationYear = new Date().getFullYear() + "";
    this.getList();
    this.getVersionList();
    this.judgeRole();
  },
  methods: {
    judgeRole() {
      //  if (auth.hasRole("ynbm_leader") || auth.hasRole("ynbm_user")) {
      //     this.isYnbm = true;
      //   }
      //   if (auth.hasRole("nhgl_user") || auth.hasRole("nhgl_leader")) {
      //     this.isNhgl = true;
      //   }
    },

    headerRowStyle(obj) {
      if (
        obj.column.property === "allocationGuideVal" ||
        obj.column.property === "allocationBaseVal" ||
        obj.column.property === "allocationConstraintVal"
      ) {
        return "tabel-bg-blue";
      } else if (
        obj.column.property === "adjustGuideVal" ||
        obj.column.property === "adjustBaseVal" ||
        obj.column.property === "adjustConstraintVal" ||
        obj.column.property === "caozuo"
      ) {
        return "tabel-bg-red";
      } else if (
        obj.column.property === "assessGuideVal" ||
        obj.column.property === "assessBaseVal" ||
        obj.column.property === "assessConstraintVal"
      ) {
        return "tabel-bg-green";
      }
    },
    tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        return "background:rgba(223,240,216,0.4)";
      } else if (columnIndex === 3) {
        return "background:rgba(242,222,222,0.4)";
      } else if (columnIndex === 4) {
        return "background:rgba(217,237,247,0.4)";
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 6) {
        if (rowIndex % this.list.length === 0) {
          return {
            rowspan: this.list.length,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    hanleClose() {
      this.exportsShow = false;
    },
    setImportDataId(data) {
      this.queryParams.importDataId = data;
      this.getList();
    },
    //获取版本号
    getVersionList() {
      rationVersionList()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.versionOption = res.data;
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300064");
        });
    },
    detail(id) {
      this.id = id;
      this.detailShow = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      const data = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        importDataId: this.queryParams.importDataId,
        allocationYear: this.queryParams.allocationYear,
        energyType: this.queryParams.energyType,
        targetType: this.queryParams.targetType,
        rationCriterionVersion: this.queryParams.rationCriterionVersion,
        sysDeptId:
          this.queryParams.sysDeptList[this.queryParams.sysDeptList.length - 1],
      };
      exportExecl("额度分配", "/energy/quota-allocation/export", data, this);
    },
    /** 查询列表 */
    async getList() {
      const that = this;
      that.loading = true;
      const data = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        importDataId: this.queryParams.importDataId,
        allocationYear: this.queryParams.allocationYear,
        energyType: this.queryParams.energyType,
        targetType: this.queryParams.targetType,
        rationCriterionVersion: this.queryParams.rationCriterionVersion,
        sysDeptId:
          this.queryParams.sysDeptList[this.queryParams.sysDeptList.length - 1],
      };

      list(data)
        .then((res) => {
          that.loading = false;
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.list = res.rows;
          that.totalList = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.loading = false;
          // this.$message.error("系统错误,请联系管理员!300071");
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 额度批量分配 */
    distribution() {
      if (this.queryParams.sysDeptList.length <= 0) {
        this.$message.warning("请选择用能单位");
        return false;
      }
      if (String(this.queryParams.energyType).length <= 0) {
        this.$message.warning("请选择能耗种类");
        return false;
      }
      if (String(this.queryParams.targetType).length <= 0) {
        this.$message.warning("请选择指标类型");
        return false;
      }
      if (!this.queryParams.rationCriterionVersion) {
        this.$message.warning("请选择参考额度标准版本号");
        return false;
      }
      if (!this.queryParams.allocationYear) {
        this.$message.warning("请选择能耗预算年份");
        return false;
      }
      const data = {
        importDataId: this.queryParams.importDataId,
        allocationYear: this.queryParams.allocationYear,
        energyType: this.queryParams.energyType,
        targetType: this.queryParams.targetType,
        rationCriterionVersion: this.queryParams.rationCriterionVersion,
        sysDeptId:
          this.queryParams.sysDeptList[this.queryParams.sysDeptList.length - 1],
      };
      quotaAllocation(data)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300072");
        });
    },
    handleUpdate(row) {
      this.model = row;
      this.show = true;
    },
    close(name) {
      this.resetForm(name);
      this.show = false;
      this.detailShow = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const data = {
            importDataId: this.queryParams.importDataId,
            allocationYear: this.queryParams.allocationYear,
            energyType: this.queryParams.energyType,
            targetType: this.queryParams.targetType,
            rationCriterionVersion: this.queryParams.rationCriterionVersion,
            sysDeptId:
              this.queryParams.sysDeptList[
                this.queryParams.sysDeptList.length - 1
              ],
            adjustBaseVal: this.model.adjustBaseVal,
            adjustConstraintVal: this.model.adjustConstraintVal,
            adjustGuideVal: this.model.adjustGuideVal,
            id: this.model.id,
          };
          adjustVal(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.close("form");
              this.getList();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!300075");
            });
        }
      });
    },
  },
};
</script>

  <style lang="scss" scoped>
::v-deep .tabel-bg-green {
  background: rgba(223, 240, 216, 0.4) !important;
}

::v-deep .tabel-bg-blue {
  background: rgba(217, 237, 247, 0.4) !important;
}

::v-deep .tabel-bg-red {
  background: rgba(242, 222, 222, 0.4) !important;
}

.flex {
  display: flex;
  justify-content: center;
  align-items: center;

  .el-icon-info {
    font-size: 18px;
    padding-left: 10px;
    vertical-align: text-bottom;
    cursor: pointer;
  }
}

.box-card {
  .clearfix {
    height: 22px;
    width: 100%;
    z-index: 99;

    span {
      opacity: 0.8;
    }
  }

  span {
    &:nth-child(1) {
      font-size: 20px;
      font-weight: 600;
      color: #333333;
    }
  }

  .constip {
    display: flex;
    align-items: center;

    .cons-tabs {
      margin-right: 20px;
    }
  }

  .unit {
    span {
      font-weight: 400;
      font-size: 14px;
      font-style: normal;
      letter-spacing: 0;
      text-decoration: none;

      &:nth-child(1) {
        color: rgb(16, 16, 16);
        margin-right: 10px;
      }

      &:nth-child(2) {
        color: rgb(247, 122, 5);
      }
    }
  }
}
</style>
